﻿using System.ComponentModel;
using System.Linq;
using System;

namespace DeepEarth.Core.Converters
{
    public class LocationRectangleTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, System.Type sourceType)
        {
            return sourceType == typeof(string);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            string inputString = value.ToString();

            string[] parts = inputString.Split(',').Select(s => s.Trim()).ToArray();

            if (!DesignerProperties.IsInDesignTool)
            {
                System.Diagnostics.Debug.Assert(parts.Length == 4);
            }

            double west = -180, south = -85, east = 180, north = 85;

            for (int i=0; i<4 ;i++)
            {
                int direction = i;

                string part = parts[i];
                string valueString = part;
                string[] namedAxis = part.Split('=').Select(s => s.Trim().ToLower()).ToArray();
                if (namedAxis.Length > 1)
                {
                    valueString = namedAxis[1].ToLower();
                    part = namedAxis[2];

                    char c = valueString[0];

                    switch (c)
                    {
                        case 'w' : direction = 0; break;
                        case 's': direction = 1; break;
                        case 'e': direction = 2; break;
                        case 'n': direction = 3; break;
                    }

                }
                          
                switch (direction)
                {
                    case 0: double.TryParse(part, out west); break;
                    case 1: double.TryParse(part, out south); break;
                    case 2: double.TryParse(part, out east); break;
                    case 3: double.TryParse(part, out north); break;                        
                    default: throw new Exception("Invalid Location Rectangle");
                }             
            }

            Location nw = new Location(north, west);
            Location se = new Location(south, east);

            return new LocationRectangle(nw, se);

        }
    }
}
